/**
 * 报销单打印设置 tab
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Popconfirm, Popover, Badge, Radio, message, Icon, Button, Spin } from 'antd';
import { getQueryUrlParam, messages } from 'share/common';
import errorMessage from 'share/errorMessage'
import SlideFrameDetail from './expense-print-detail'
import TableList from '../table-list'
import settingService from '../request-and-expense-settings.service'
import 'styles/request-and-expense-settings/expense-prin.scss';
import process from 'images/expense/banner.png';
import processEn from 'images/expense/banner-en.png'
import immediately from 'images/expense/button.png';
import immediatelyEn from 'images/expense/button-en.png';
import openSlideFrame from 'share/openSlideFrame';
import SlideFrame from 'components/slide-frame'
import PrintFree from 'containers/request-and-expense-settings/expense-setting/print-free'
import Info from 'components/info';
import Condition from 'components/condition';
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";
import JumpConfigCenter from '../../setting/configuration-center/jump-config-center';
import Space from 'components/space';

const RadioGroup = Radio.Group;
const { If, Else } = Condition;

class ExpensePrint extends Component {

  state = {
    loading: false,
    isShowAd: true,
    infoLoading: false,
    printFree: {
      attributes: [
        {
          title: messages('expense-7.key80')/*已开通免打印*/,
          dataIndex: 'expenseReportPrintFreeDesc',
          span: 24,
          widthFix: false,
          colon: true
        }
      ],
      dataSource: {}
    }
  };

  infoData = {
    dataSource: { explain: messages('expense-7.key81')/*您可在此页面报销单打印模版内容及相关控制规则*/ },
    attributes: [{ title: messages('expense-7.key82')/*说明*/, dataIndex: 'explain', span: 24 }]
  };

  slideFrameInfo = {
    title: messages('expense-7.key83')/*报销单打印设置*/,
    content: SlideFrameDetail
  };

  defaultInfo = {
    title: messages('expense-7.key83')/*报销单打印设置*/,
    data: [{
      title: messages('expense-7.key78')/*模版内容设置*/,
      titleStyle: { marginTop: 0 },
      label: messages('expense-7.key54')/*报销单打印方向*/,
      value: messages('expense-7.key44')/*横向*/,
      extra: messages('expense-7.key55')/*配置报销单打印的列表方向为横向或竖向*/
    }, {
      label: messages('expense-7.key56')/*费用类型小计*/,
      value: messages('expense-7.key46')/*不打印*/,
      extra: messages('expense-7.key57')/*配置报销单是否打印“费用类型小计”*/
    }, {
      label: messages('expense-7.key58')/*无票费用（包括第三方费用，滴滴）*/,
      value: messages('common.print')/*打印*/,
      extra: messages('expense-7.key59')/*配置无票费用是否打印（包括第三方费用，滴滴）*/
    }, {
      label: messages('expense-7.key60')/*费用事由说明*/,
      value: messages('common.print')/*打印*/,
      extra: messages('expense-7.key61')/*配置报销单是否打印费用“事由说明”*/
    }, {
      label: messages('expense-7.key62')/*替票与替票理由*/,
      value: messages('common.print')/*打印*/,
      extra: messages('expense-7.key63')/*配置开启“替票”功能时，报销单是否打印员工填写的替票理由*/
    }, {
      label: messages('expense-7.key64')/*费用只有1行分摊*/,
      value: messages('expense-7.key46')/*不打印*/,
      extra: messages('expense-7.key65')/*费用只有1行分摊，是否在报销单打印页面显示*/
    }, {
      label: messages('expense-7.key66')/*阶梯里程详情*/,
      value: messages('expense-7.key46')/*不打印*/,
      extra: messages('expense-7.key67')/*当启用阶梯模式里程补贴时，报销单打印里程补贴费用是否显示阶梯里程详情列表*/
    }, {
      label: messages('expense-7.key68')/*关联银行卡信息和付款信息*/,
      value: messages('common.print')/*打印*/,
      extra: messages('expense-7.key69')/*配置是否打印报销单关联的银行卡信息和付款信息*/
    }, {
      label: messages('expense-7.key70')/*审批历史*/,
      value: messages('common.print')/*打印*/,
      extra: messages('expense-7.key71')/*配置是否打印报销单的审批历史*/
    }, {
      label: messages('expense-7.key72')/*每页打印发票份数*/,
      value: messages('expense-7.key47')/*一份*/,
      extra: messages('expense-7.key73')/*配置报销单打印时每页打印的发票份数*/
    }, {
      title: messages('expense-7.key79')/*打印控制与通知*/,
      label: messages('expense-7.key74')/*允许员工打印自己的已审核通过的报销单*/,
      value: messages('expense-7.key49')/*允许*/,
      extra: messages('expense-7.key75')/*【我的报销】页面查看自己的已审核通过的报销单详情，是否显示打印按钮*/
    }, {
      label: messages('expense-7.key76')/*员工打印关联发票袋的报销单*/,
      value: messages('expense-7.key46')/*不打印*/,
      extra: messages('expense-7.key77')/*报销单关联发票袋后，是否对员工显示报销单打印按钮*/
    }]
  };

  searchForm = [{
    id: 'levelCodes',
    dataIndex: 'levelCode',
    label: messages('expense-7.key41')/*层级*/,
    component: (
      <RadioGroup>
        <Radio value="COMPANY">{messages('expense-7.key84')/*公司*/}</Radio>
        <Radio value="TENANT">{messages('expense-7.key85')/*租户*/}</Radio>
      </RadioGroup>
    ),
    tagParser: value => {
      return value === "COMPANY" ? messages('expense-7.key84')/*公司*/ : messages('expense-7.key85')/*租户*/;
    }
  }, {
    id: 'distLevelOrgIds',
    dataIndex: 'distLevelOrgName',
    label: messages('expense-7.key86')/*启用公司*/,
    component: 'Chooser',
    props: {
      labelKey: 'name',
      valueKey: 'id',
      type: 'priority_company'
    },
    parser: value => ({
      distLevelOrgIds: value ? value.map(item => item.id) : null
    })
  }];

  columns = [{
    title: messages('expense-7.key41')/*层级*/,
    dataIndex: 'levelCode',
    render: value => value === 'COMPANY' ? messages('expense-7.key84')/*公司*/ : messages('expense-7.key85')/*租户*/
  }, {
    title: messages('expense-7.key34')/*所属组织*/,
    dataIndex: 'levelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('expense-7.key86')/*启用公司*/,
    dataIndex: 'distLevelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('common.column.status')/*状态*/,
    dataIndex: 'enabled',
    width: '10%',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
      />
    )
  }, {
    title: messages('common.operation')/*操作*/,
    dataIndex: 'expRptPrintOptId',
    width: '10%',
    render: (value, record) => (
      record.readOnly ? (
        <div>
          <span className="font-disabled" onClick={e => e.stopPropagation()}>{messages('common.copy')/*复制*/}</span>
          <span className="ant-divider" />
          <span className="font-disabled" onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</span>
        </div>
      ) : (
        <div>
          <a onClick={() => this.slideFrameInfo.params = { isCopy: true }}>
            {messages('common.copy')/*复制*/}
          </a>
          <span className="ant-divider" />
          <Popconfirm
            title={messages('common.confirm.delete')/*确定要删除吗？*/}
            onConfirm={() => this.handleDelete(value)}
          >
            <a onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</a>
          </Popconfirm>
        </div>
      )
    )
  }];

  componentDidMount() {
    this.getPrintConfig()
      .finally(() => {
        const { printFree } = this.state;
        const isShowOpenAd = getQueryUrlParam('fromUnboxSetting') === 'Y';
        if (!printFree.dataSource.expenseReportPrintFreeEnabled && isShowOpenAd) {
          this.handleAd(null, 'jumpAd');
        }
      });
  }

  service = (page, size, searchParams) => {
    let params = searchParams;
    params.levelCodes === 'ALL' && (params.levelCodes = undefined);
    params.levelCodes && (params.levelCodes = [params.levelCodes]);
    return settingService.getExpensePrintList(page, size, params);
  };

  handleDelete = (id) => {
    this.setState({ loading: true });
    return settingService.deleteExpensePrint(id).then(() => {
      this.setState({ loading: false });
      this.advancedTableRef.getList();
      message.success(messages('common.delete.success',{arg1: ''})/*{arg1} 删除成功*/);
    }).catch(e => {
      this.setState({ loading: false });
      errorMessage(e.response);
    })
  };

  afterClose = refresh => {
    this.slideFrameInfo.params = { isCopy: false };
    if (typeof refresh === 'boolean' && refresh) {
      this.advancedTableRef.getList();
    }
  };

  openAdvertisement = (isHide) => {
    openSlideFrame.openAdvertisement({
      isHide
    }, {
      afterClose: (flag) => {
        flag && this.getPrintConfig();
      }
    }, this);
  };

  openPrintFree = (params) => {
    SlideFrame.open({
      title: !!params ? messages('common.edit')/*编辑*/ : messages('common.create')/*新建*/,
      content: PrintFree,
      params,
      afterClose: (flag) => {
        flag && this.getPrintConfig();
      }
    }, this);
  };

  getPrintConfig = async () => {
    const { printFree } = this.state;
    this.setState({ infoLoading: true });
    const ret = await settingService.getFreePrintPasteConfig();
    printFree.dataSource = ret.data;
    printFree.dataSource.id = '111';
    await this.setState({ printFree, infoLoading: false });
  };

  handleAd = (e, flag) => {
    e && e.stopPropagation();
    if (flag === 'jumpAd') {
      this.openAdvertisement(false);
      return;
    }

    if (flag === 'open') {
      this.openPrintFree();
    }
  };

  handleEditHead = () => {
    const { printFree: { dataSource } } = this.state;
    this.openPrintFree(dataSource)
  };

  handleMore = () => {
    this.openAdvertisement(true);
  };

  render() {
    const { loading, infoLoading, printFree: { attributes, dataSource } } = this.state;
    const { language } = this.props;
    let tableParams =  batchOperations({
      rowKey: 'expRptPrintOptId'
    }, [{
      type: 'DELETE',
      service: settingService.batchDeleteExpensePrint,
      onOk: () => this.advancedTableRef.getList()
    }, {
      type: 'ENABLE',
      service: settingService.batchOpenOrCloseExpensePrint,
      onOk: () => this.advancedTableRef.getList()
    }, {
      type: 'DISABLE',
      service: settingService.batchOpenOrCloseExpensePrint,
      onOk: () => this.advancedTableRef.getList()
    }], this);
    return (
      <article className="expense-print">
        <TableList
          infoData={this.infoData}
          slideFrameInfo={this.slideFrameInfo}
          defaultInfo={this.defaultInfo}
          afterClose={this.afterClose}
          title={messages('expense-7.key87')/*打印模板设置*/}
          tableParams={{
            loading,
            rowKey: 'expRptPrintOptId',
            searchForm: this.searchForm,
            columns: this.columns,
            service: this.service,
            onRef: ref => this.advancedTableRef = ref,
            ...tableParams
          }}
          children={
            infoLoading
              ? <Spin/>
              : <Condition>
                  <If value={dataSource.expenseReportPrintFreeEnabled}>
                    <Info
                      title={messages('expense-7.key88')/*免打印设置*/}
                      loading={infoLoading}
                      className="expense-print-info"
                      attributes={attributes}
                      dataSource={dataSource}
                    >
                      <a style={{ marginRight: 20 }} onClick={this.handleMore}>
                        <Icon
                          type="bulb"/>&nbsp;{messages('expense-7.key89')/*了解更多*/}
                      </a>
                      <Button type='primary' onClick={this.handleEditHead}>{messages('common.edit')/*编辑*/}</Button>
                    </Info>
                  </If>
                  <Else>
                    <Spin spinning={infoLoading}>
                      <section className="expense-print-header" onClick={(e) => this.handleAd(e, 'jumpAd')}>
                        <img src={language.code === 'en' ? processEn : process} alt="" className="expense-print-ad"/>
                        <img
                          src={language.code === 'en' ? immediatelyEn : immediately}
                          alt=""
                          className="expense-print-button"
                          onClick={(e) => this.handleAd(e, 'open')}
                        />
                      </section>
                    </Spin>
                  </Else>
                  <JumpConfigCenter tab={'expense-print'} style={{marginBottom: '12px',marginTop: '12px'}}/>
              </Condition>
          }
        />
      </article>
    );
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
  }
}

export default connect(mapStateToProps)(ExpensePrint)
